package com.untrance.shop.web.controller;

import com.untrance.shop.common.utils.JpaUtils;
import com.untrance.shop.common.utils.PagerUtils;
import com.untrance.shop.common.vo.CategoryVO;
import com.untrance.shop.common.vo.PagerParametersVO;
import com.untrance.shop.common.vo.ProductVO;
import com.untrance.shop.core.builder.vo.ProductVOBuilder;
import com.untrance.shop.core.service.CategoryService;
import com.untrance.shop.core.service.ProductService;
import com.untrance.shop.model.Product;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

/**
 * @author eugene zadyra
 */
@Controller
public class IndexController {

	private static final Logger log = LoggerFactory.getLogger(IndexController.class);

	@Autowired
	ProductService productService;
	@Autowired
	CategoryService categoryService;

	@Transactional(readOnly = true)
	@RequestMapping("/index.html")
	public ModelAndView getHomePage(@RequestParam(value = "page", required = false, defaultValue = "1") Integer page,
									@RequestParam(value = "per_page", required = false, defaultValue = "12") Integer perPage,
									@RequestParam(value = "id", required = false) String categoryId) {
		log.info("getHomePage +");
		ModelAndView mav = new ModelAndView("index");
		mav.addObject("category_id", categoryId);
		Integer count = productService.getProductsCountInCategory(JpaUtils.getKey(categoryId));
		PagerParametersVO pagerData = PagerUtils.calculatePagerParameters(page, count, perPage);
		mav.addObject("pagerData", pagerData);
		List<Product> list = productService.getLimitedAmountOfProducts(JpaUtils.getKey(categoryId), page, perPage);
		List<ProductVO> listVO = new ProductVOBuilder().createVOList(list);
		mav.addObject("products", listVO);
		List<CategoryVO> categoriesVO = categoryService.getCategoriesVOTreeByKey(JpaUtils.getKey(categoryId));
		mav.addObject("categories", categoriesVO);
		log.info("getHomePage -");
		return mav;
	}

}
